package com.example.yuejian.activity;

import android.Manifest;
import android.app.FragmentManager;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.yuejian.Bean.Success;
import com.example.yuejian.R;
import com.example.yuejian.listener.ClubListener;
import com.example.yuejian.model.AddPostModel;
import com.example.yuejian.orther.ImageBaseActivity;
import com.example.yuejian.orther.PhotoUtils;
import com.example.yuejian.orther.UserDailog;

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;


public class AddPost  extends ImageBaseActivity implements View.OnClickListener,ClubListener<Success> {

    int REQUEST_CODE = 1;
    private static final int CODE_GALLERY_REQUEST = 0xa0;
    private static final int CODE_CAMERA_REQUEST = 0xa1;
    private static final int CODE_RESULT_REQUEST = 0xa2;
    private File fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/photo.png");
    private File fileCropUri = new File(Environment.getExternalStorageDirectory().getPath() + "/crop_photo.png");
    private Uri imageUri;
    private Uri cropImageUri;
    private Bitmap bitmap;
    File file  = null ;
    private ImageView show,add,back;
    private EditText edit_content;
    private Button send;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_post);
        init();
        Event();

    }

    private void init(){
        show = (ImageView)findViewById(R.id.show);
        add = (ImageView)findViewById(R.id.add);
        back = (ImageView)findViewById(R.id.back);
        edit_content = (EditText)findViewById(R.id.edit_content);
        send = (Button)findViewById(R.id.send);

    }

    private void Event(){
        add.setOnClickListener(this);
        back.setOnClickListener(this);
        send.setOnClickListener(this);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        int output_X = 480, output_Y = 480;
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CODE_CAMERA_REQUEST://拍照完成回调
                    cropImageUri = Uri.fromFile(fileCropUri);
                    PhotoUtils.cropImageUri(this, imageUri, cropImageUri, 1, 1, output_X, output_Y, CODE_RESULT_REQUEST);
                    break;
                case CODE_GALLERY_REQUEST://访问相册完成回调
                    if (hasSdcard()) {
                        cropImageUri = Uri.fromFile(fileCropUri);
                        Uri newUri = Uri.parse(PhotoUtils.getPath(this, data.getData()));
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                            newUri = FileProvider.getUriForFile(this, "com.example.yuejian.fileprovider", new File(newUri.getPath()));
                        PhotoUtils.cropImageUri(this, newUri, cropImageUri, 1, 1, output_X, output_Y, CODE_RESULT_REQUEST);
                    } else {
                        Toast.makeText(this, "设备没有SD卡!", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case CODE_RESULT_REQUEST:
                    bitmap = PhotoUtils.getBitmapFromUri(cropImageUri, this);
                    if (bitmap != null) {

                        show.setImageBitmap(bitmap);
                    }
                    break;
            }
        }

    }

    public void alterUserDialog() {
        FragmentManager fragmentManager = getFragmentManager();
        UserDailog userDailog = new UserDailog();
        userDailog.show(fragmentManager, "hello,tomorrow!");
    }

    public void takePictureInCamera(){
        requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE}, new ImageBaseActivity.RequestPermissionCallBack() {
            @Override
            public void granted() {
                if (hasSdcard()) {
                    imageUri = Uri.fromFile(fileUri);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                        //通过FileProvider创建一个content类型的Uri
                        imageUri = FileProvider.getUriForFile(AddPost.this, "com.example.yuejian.fileprovider", fileUri);
                    PhotoUtils.takePicture(AddPost.this, imageUri, CODE_CAMERA_REQUEST);
                } else {
                    Toast.makeText(AddPost.this, "设备没有SD卡！", Toast.LENGTH_SHORT).show();
                    Log.e("asd", "设备没有SD卡");
                }
            }

            @Override
            public void denied() {
                Toast.makeText(AddPost.this, "Some permissions fail, and normal functions are affecte", Toast.LENGTH_LONG).show();
            }
        });

    }

    public void takePictureInAlbum(){
        requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, new ImageBaseActivity.RequestPermissionCallBack() {
            @Override
            public void granted() {
                PhotoUtils.openPic(AddPost.this, CODE_GALLERY_REQUEST);
            }

            @Override
            public void denied() {
                Toast.makeText(AddPost.this, "Some permissions fail, and normal functions are affected", Toast.LENGTH_LONG).show();
            }
        });
    }
    public static boolean hasSdcard() {
        String state = Environment.getExternalStorageState();
        return state.equals(Environment.MEDIA_MOUNTED);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.add:
                alterUserDialog();
                break;
            case R.id.send:
                userSendPost();
                break;
            case R.id.back:
                finish();
        }
    }

    @Override
    public void onResponse(Success success) {
        Toast.makeText(this,"发送成功",Toast.LENGTH_LONG).show();
    }

    @Override
    public void onFail(String msg) {
        Toast.makeText(this,"发送失败",Toast.LENGTH_LONG).show();
    }

    private void userSendPost(){
        try {
            file = new File(new URI(cropImageUri.toString()));
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part body = MultipartBody.Part.createFormData("pic", file.getName(),requestBody);
        String mContent = edit_content.getText().toString();
        AddPostModel addPostModel = new AddPostModel();
        addPostModel.addPost(this,2,mContent,body);
    }
}
